首先新增一個Fragment,名稱為BlankFragment
再新增一個Package,名稱為menuFragment
然後在menuFragment底下,新增三個HomepageFragment、CharacterFragment、PlotFragment
再到drawable新增三張.png的圖片,檔名分別為cat、pikachu、plot
修改menuFragment底下三個Fragment的layout,這裡示範其中一個(其他兩個改掉background裡的圖片就好)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".menuFragment.CharacterFragment">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/pikachu"/>
</FrameLayout>
MainActivity:
使用BottomNavigationView控制Fragment
public class MainActivity extends AppCompatActivity {
final FragmentManager fragmentManager = getSupportFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.nav);
// 取消元件自帶的動畫
bottomNavigationView.getMenu().setGroupCheckable(0, false, false);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BlankFragment fragment = new BlankFragment();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.homePage:
FragmentTransaction homePageTransaction = fragmentManager.beginTransaction();
homePageTransaction.replace(R.id.frag, new HomepageFragment());
homePageTransaction.commit();
break;
case R.id.character:
FragmentTransaction characterTransaction = fragmentManager.beginTransaction();
characterTransaction.replace(R.id.frag, new CharacterFragment());
characterTransaction.commit();
break;
case R.id.plot:
FragmentTransaction plotTransaction = fragmentManager.beginTransaction();
plotTransaction.replace(R.id.frag, new PlotFragment());
plotTransaction.commit();
break;
}
return true;
}
});
}
}
謝謝大家願意花時間閱讀,小弟弟我在此鞠躬